<template>
  <div class="dialog_box">
    <el-dialog v-model="visible" width="1000px" :title="`${pageType == 'CREATE' ? '新建' : pageType == 'EDIT' ? '编辑' : '查看'}流程`" @closed="onClose">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto" :disabled="pageType == 'LOOK'">
        <div class="item">
          <el-form-item label="流程名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入流程名称" maxlength="15" show-word-limit />
          </el-form-item>
          <el-form-item label="流程描述" prop="desc">
            <el-input placeholder="请输入流程描述" v-model="formData.desc" maxlength="150" show-word-limit :rows="6" type="textarea" />
          </el-form-item>
        </div>
        <el-form-item label="阶段列表">
          <!-- 拖拽 -->
          <el-table v-if="showTable" header-row-class-name="table_header_title" class="configure-table-box" id="tableRef" :data="formData.stages" row-key="id" style="width: 100%" :header-cell-style="{ background: '#fafafa', color: '#101010' }" stripe>
            <el-table-column label="阶段类型">
              <template #default="scope"> {{ scope.$index < formData.stages.length - 2 ? '进行阶段' : '结束阶段' }} </template>
            </el-table-column>
            <el-table-column prop="stock_qty" label="阶段名称">
              <template #default="scope">
                <el-input v-model="formData.stages[scope.$index].name" placeholder="请输入阶段名称" maxlength="10" show-word-limit size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="stock_qty" label="赢率">
              <template #default="scope">
                <div class="discount">
                  <el-input-number
                    v-model="formData.stages[scope.$index].win_rate"
                    :min="0"
                    :max="100"
                    :controls="false"
                    :precision="0"
                    size="small"
                    placeholder="0~100"
                    :disabled="scope.$index == formData.stages.length - 1 || scope.$index == formData.stages.length - 2"
                  />
                  %
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="pageType != 'LOOK'" prop="stock_qty" label="操作">
              <template #default="scope">
                <div v-if="scope.row.setting_stage != 100 && scope.row.setting_stage != 101" class="btn_box">
                  <img v-if="scope.$index > 0 && scope.$index < formData.stages.length - 2" class="can-sort try" src="@/assets/customer/sort-icon.png" alt="" />
                  <el-icon v-if="formData.stages.length - 3 == scope.$index" @click="onAdd">
                    <Plus />
                  </el-icon>
                  <el-icon v-if="formData.stages.length > 3 && scope.$index > 0" @click="onDelete(scope.$index)">
                    <Delete />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="使用范围" class="use_range">
          <el-radio-group v-model="formData.use_range">
            <el-radio :label="1">全部</el-radio>
            <el-radio :label="2">指定部门员工</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.use_range == 2" :prop="onEmployeRule" class="use_range_mg10">
          <div class="form-staffs">
            <div class="staffs">
              <el-tag
                v-for="item in employees"
                :key="item.name"
                :class="item.type == 'user' ? 'staffs_item' : 'depart'"
                :closable="pageType != 'LOOK'"
                @close="handleClose(item)"
                :type="item.id"
                style="height: 22px; line-height: 22px; margin-right: 6px; color: #35383a; border: 1px solid #fffaf9; border-radius: 1px 1px 1px 1px; background: #fffaf9"
              >
                {{ item.name }}
              </el-tag>
            </div>
          </div>
          <div>
            <el-button @click="openDepart">选择员工</el-button>
          </div>
        </el-form-item>
        <el-form-item label="流程状态">
          <el-switch v-model="formData.state" :active-value="2" :inactive-value="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button v-if="pageType != 'LOOK'" @click="onSubmit(formRef)" type="primary">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <ZWDepart ref="DepartRef" @submit="getDepart" :type="1" />
</template>

<script setup lang="ts">
  import ZWDepart from '@/components/ZWDepart.vue'
  import { workflowAdd, workflowInfo, workflowEdit } from '@/api/salesleads/salesmanagement/business'
  import { getSetionId } from '@/utils/utils'
  import Sortable from 'sortablejs'
  import { ElMessage } from 'element-plus'
  import { computed, nextTick, ref } from 'vue'
  import { reactive, defineEmits } from 'vue'
  const emit = defineEmits(['submit'])
  const visible: any = ref(false)
  const formRef = ref<any>()
  const categoryList = ref([])
  const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
  }
  const formData = ref<any>({
    name: '', //名称
    desc: '', //描述
    use_range: 1, //使用范围 1：全部 2：指定员工
    staff_ids: [], //员工ids
    dept_ids: [], //部门ids
    state: 2, //状态 1：关闭 2：开启
    stages: [
      { name: '初始阶段', win_rate: 0, setting_stage: 1 },
      { name: '', win_rate: 0, setting_stage: 1 },
      { name: '', win_rate: 0, setting_stage: 1 },
      { name: '赢单', win_rate: 100, setting_stage: 100 },
      { name: '输单', win_rate: 0, setting_stage: 101 }
    ] //阶段列表
  })
  const rules = reactive<any>({
    name: [{ required: true, message: '请输入流程名称', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入流程描述', trigger: 'blur' }],
    staff_ids: [{ required: true, message: '请选择员工', trigger: 'blur' }]
  })
  // 选择员工
  const DepartRef = ref<any>() // 部门弹框类型
  const employees = ref<any>([])
  const openDepart = () => {
    DepartRef.value.isMember = false
    DepartRef.value.selectedMember = [...employees.value]
    DepartRef.value.departVisble = true
  }
  // 获取部门成员
  const getDepart = (res: any) => {
    console.log('获取成员信息', res)
    employees.value = res
    res.forEach((item: any) => {
      if (item.type == 'user') {
        formData.value.staff_ids.push(item.id)
      } else {
        formData.value.dept_ids.push(item.id)
      }
    })
    // formData.value.staff_ids = getSetionId('id', employees.value)
    console.log('获取部门成员', res)
  }
  // 员工移除
  const handleClose = (tag: any) => {
    console.log(tag, '2222')
    employees.value = employees.value.filter((item: any) => item.id !== tag.id)
    formData.value.dept_ids = []
    formData.value.staff_ids = []
    employees.value.forEach((item: any) => {
      if (item.type == 'user') {
        formData.value.staff_ids.push(item.id)
      } else {
        formData.value.dept_ids.push(item.id)
      }
    })
    // formData.value.staff_ids = getSetionId('id', employees.value)
    DepartRef.value.removeItem(tag)
  }
  // 员工校验
  const onEmployeRule = computed(() => {
    let num = formData.value.staff_ids.length + formData.value.dept_ids.length
    return num ? '' : 'staff_ids'
  })
  const pageType = ref('CREATE')
  const onAdd = () => {
    if (pageType.value != 'LOOK') {
      formData.value.stages.splice(formData.value.stages.length - 2, 0, {
        name: '',
        win_rate: 0,
        setting_stage: 1
      })
    }
  }
  const onDelete = (index: any) => {
    if (pageType.value != 'LOOK') {
      formData.value.stages.splice(index, 1)
    }
  }
  const onSubmit = async (formEl: any) => {
    if (!formEl) return
    await formEl.validate((valid: any, fields: any) => {
      if (valid) {
        if (
          formData.value.stages.every((item: any, index: number) => {
            let flag = true
            if (index < formData.value.stages.length - 3) {
              console.log(item.win_rate < formData.value.stages[index + 1].win_rate)
              flag = item.win_rate <= formData.value.stages[index + 1].win_rate
            }
            return flag
          })
        ) {
          if (formData.value.stages.every((item: any) => item.name != '')) {
            formData.value.workflow_id
              ? workflowEdit(formData.value).then((res: any) => {
                  ElMessage.success('编辑流程成功')
                  emit('submit')
                  visible.value = false
                })
              : workflowAdd(formData.value).then((res: any) => {
                  ElMessage.success('新增流程成功')
                  emit('submit')
                  visible.value = false
                })
          } else {
            ElMessage.error('阶段名称不能为空')
          }
        } else {
          ElMessage.warning('进行阶段赢率后一个不能小于前一个')
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  // 排序的方法
  const showTable = ref(true)
  // const tableRowClassName = (row: any) => {
  //   if (row.rowIndex == 0 || row.rowIndex == formData.value.stages.length - 1 || row.rowIndex == formData.value.stages.length - 2) {
  //     return 'no-sort'
  //   }
  //   return 'can-sort'
  // }

  const setSortableFun = () => {
    let copyTableList: any
    let nowIndex: any
    nextTick(() => {
      const el = document.querySelector('#tableRef .el-table__body-wrapper  tbody')
      let SortableBox = new Sortable(el, {
        animation: 100,
        sort: true,
        delay: 0,
        delayOnTouchOnly: false,
        handle: '.try',
        filter: '.no-sort',
        onChoose: function (evt: any) {
          nowIndex = evt.oldIndex
          console.log(evt.oldIndex)
        },
        onMove: function (evt: any, originalEvent: any) {
          console.log(evt)
          // console.log('移动中', evt)
          // let index = evt.related.querySelector('.table-item').getAttribute('data-id')
          // if (index == 0 || index == formData.value.stages.length - 1 || index == formData.value.stages.length - 2) {
          //   return false
          // }
          // return true
        },
        //
        onEnd: (evt: any) => {
          console.log(evt, '----------------')
          console.log(evt.oldIndex, '元素在旧父级中的旧索引')
          console.log(evt.newIndex, '元素在新父级中的新索引')
          console.log(evt.oldDraggableIndex, '元素在旧父级中的旧索引，仅计数可拖动的元素')
          console.log(evt.newDraggableIndex, '元素在新父级中的新索引，仅计数可拖动元素')
          copyTableList = JSON.parse(JSON.stringify(formData.value.stages))
          const data = copyTableList.splice(evt.oldIndex, 1)[0]
          copyTableList.splice(evt.newIndex, 0, data)
          let next_id, pre_id
          if (copyTableList[evt.newIndex - 1]) {
            pre_id = copyTableList[evt.newIndex - 1].source_id
          }
          if (copyTableList[evt.newIndex + 1]) {
            next_id = copyTableList[evt.newIndex + 1].source_id
          }
          let arr: any = []
          copyTableList.forEach((item: any, index: number) => {
            arr.push({ id: item.id, sort: index + 1 })
          })
          console.log(copyTableList)
          if (evt.newIndex < 1 || evt.newIndex > formData.value.stages.length - 3) {
            copyTableList = JSON.parse(JSON.stringify(formData.value.stages))
            formData.value.stages = []
            nextTick(() => {
              formData.value.stages = copyTableList
            })
          } else {
            formData.value.stages = []
            nextTick(() => {
              formData.value.stages = copyTableList
            })
          }
        }
      })
    })
  }
  const onProcessShow = (type: any, row?: any) => {
    nextTick(() => {
      setSortableFun()
    })
    console.log('查看流程', pageType.value)
    pageType.value = type
    if (pageType.value != 'CREATE') {
      workflowInfo({ workflow_id: row.id }).then((res: any) => {
        console.log('查看流程', res)
        formData.value = {
          workflow_id: res.id,
          name: res.name,
          desc: res.desc,
          use_range: res.use_range,
          staff_ids: res.staff_ids,
          dept_ids: res.dept_ids,
          state: res.state,
          stages: res.stages
        }
        let user = res.staff_list.map((item: any) => ({
          ...item,
          type: 'user'
        }))
        let dept_list = res.dept_list.map((item: any) => ({
          ...item,
          type: 'depart'
        }))
        employees.value = [...user, ...dept_list]
      })
    }
    visible.value = true
  }
  const onClose = () => {
    formData.value = {
      name: '', //名称
      desc: '', //描述
      use_range: 1, //使用范围 1：全部 2：指定员工
      staff_ids: [], //员工ids
      dept_ids: [], //部门ids
      state: 2, //状态 1：关闭 2：开启
      stages: [
        { name: '初始阶段', win_rate: 0, setting_stage: 1 },
        { name: '', win_rate: 0, setting_stage: 1 },
        { name: '', win_rate: 0, setting_stage: 1 },
        { name: '赢单', win_rate: 100, setting_stage: 100 },
        { name: '输单', win_rate: 0, setting_stage: 101 }
      ] //阶段列表
    }
    pageType.value = 'CREATE'
    employees.value = []
  }
  defineExpose({
    onProcessShow,
    pageType
  })
</script>

<style scoped lang="scss">
  .use_range {
    margin-bottom: 0;
  }
  .use_range_mg10 {
    margin-bottom: 10px;
  }
  .dialog_box {
    :deep(.el-dialog) {
      .el-dialog__header {
        border-bottom: 1px solid #eaeaea;
      }

      .el-dialog__body {
        padding: 25px;
        border-bottom: 1px solid #eaeaea;
      }
    }

    .item {
      width: 50%;
    }

    // 员工选择
    .form-staffs {
      display: flex;
      margin-bottom: 10px;

      .title {
        margin-right: 12px;
      }

      .staffs {
        &_item {
          height: 22px;
          line-height: 22px;
          margin-right: 6px;
          // padding: 0;
          color: #35383a;
          border: 1px solid #fffaf9;
          border-radius: 1px 1px 1px 1px;
          background: #fffaf9;
        }

        :deep .el-tag .el-icon {
          width: 12px;
          height: 12px;
          color: #ffffff;
          background: #d9d9d9;
        }

        :deep .el-tag .el-icon svg {
          margin: 0px;
        }

        :deep .el-tag .el-tag__close:hover {
          background: #d9d9d9;
        }

        :deep span.el-tag.el-tag--light.staffs_item:before {
          content: '';
          display: inline-block;
          width: 10px;
          height: 11px;
          background: url('@/assets/image/LiveCode/people_icon.png') center/100% no-repeat;
          margin-right: 10px;
        }

        :deep span.el-tag.el-tag--light.depart:before {
          content: '';
          display: inline-block;
          width: 10px;
          height: 11px;
          background: url('/static/newDepart.png') center/100% no-repeat;
          margin-right: 10px;
        }
      }
    }

    .discount {
      display: flex;
      align-items: center;
    }

    .btn_box {
      display: flex;
      align-items: center;
      font-size: 23px;

      img {
        width: 20px;
        margin-right: 15px;
      }

      .el-icon {
        margin-right: 15px;
        cursor: pointer;
      }
    }
  }
</style>
